﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using ZXing.QrCode.Internal;

namespace HCDV
{
    /// <summary>
    /// 描述：条形码和二维码帮助类
    /// 时间：2018-02-18
    /// </summary>
    public class BarcodeHelper
    {
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="text">内容</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static Bitmap Generate1(string text, int width, int height)
        {
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            QrCodeEncodingOptions options = new QrCodeEncodingOptions()
            {
                DisableECI = true,//设置内容编码
                CharacterSet = "UTF-8", //设置二维码的宽度和高度
                Width = width,
                Height = height,
                Margin = 1//设置二维码的边距,单位不是固定像素
            };

            writer.Options = options;
            Bitmap map = writer.Write(text);
            return map;
        }

        /// <summary>
        /// 生成一维条形码
        /// </summary>
        /// <param name="text">内容</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static Bitmap Generate2(string text, int width, int height)
        {
            BarcodeWriter writer = new BarcodeWriter();
            //使用ITF 格式，不能被现在常用的支付宝、微信扫出来
            //如果想生成可识别的可以使用 CODE_128 格式
            //writer.Format = BarcodeFormat.ITF;
            writer.Format = BarcodeFormat.CODE_39;
            EncodingOptions options = new EncodingOptions()
            {
                Width = width,
                Height = height,
                Margin = 2
            };
            writer.Options = options;
            Bitmap map = writer.Write(text);
            return map;
        }

        /// <summary>
        /// 生成带Logo的二维码
        /// </summary>
        /// <param name="text">内容</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        public static Bitmap Generate3(string text, int width, int height)
        {
            //Logo 图片
            string logoPath = System.AppDomain.CurrentDomain.BaseDirectory + @"\img\logo.png";
            Bitmap logo = new Bitmap(logoPath);
            //构造二维码写码器
            MultiFormatWriter writer = new MultiFormatWriter();
            Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
            hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //hint.Add(EncodeHintType.MARGIN, 2);//旧版本不起作用，需要手动去除白边

            //生成二维码 
            BitMatrix bm = writer.encode(text, BarcodeFormat.QR_CODE, width + 30, height + 30, hint);
            bm = deleteWhite(bm);
            BarcodeWriter barcodeWriter = new BarcodeWriter();
            Bitmap map = barcodeWriter.Write(bm);

            //获取二维码实际尺寸（去掉二维码两边空白后的实际尺寸）
            int[] rectangle = bm.getEnclosingRectangle();

            //计算插入图片的大小和位置
            int middleW = Math.Min((int)(rectangle[2] / 3), logo.Width);
            int middleH = Math.Min((int)(rectangle[3] / 3), logo.Height);
            int middleL = (map.Width - middleW) / 2;
            int middleT = (map.Height - middleH) / 2;

            Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);
            using (Graphics g = Graphics.FromImage(bmpimg))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(map, 0, 0, width, height);
                //白底将二维码插入图片
                g.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
                g.DrawImage(logo, middleL, middleT, middleW, middleH);
            }
            return bmpimg;
        }

        /// <summary>
        /// 删除默认对应的空白
        /// </summary>
        /// <param name="matrix"></param>
        /// <returns></returns>
        private static BitMatrix deleteWhite(BitMatrix matrix)
        {
            int[] rec = matrix.getEnclosingRectangle();
            int resWidth = rec[2] + 1;
            int resHeight = rec[3] + 1;

            BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
            resMatrix.clear();
            for (int i = 0; i < resWidth; i++)
            {
                for (int j = 0; j < resHeight; j++)
                {
                    if (matrix[i + rec[0], j + rec[1]])
                        resMatrix[i, j] = true;
                }
            }
            return resMatrix;
        }


        // asset=“要生成的字符串”；
        public static Bitmap CreateQRCode(string asset)
        {
            EncodingOptions options = new QrCodeEncodingOptions
            {
                DisableECI = true,
                CharacterSet = "UTF-8",
                Width = 120,
                Height = 120
            };
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            writer.Options = options;
            return writer.Write(asset);
        }
        //生成图片的方法
        public static Image GetPrintPicture(Bitmap image, string[] asset, int picWidth, int picHeight)
        {
            Bitmap printPicture = new Bitmap(picWidth, picHeight);
            int height = 5;
            Font font = new Font("黑体", 10f);
            Graphics g = Graphics.FromImage(printPicture);
            Brush brush = new SolidBrush(Color.Black);

            g.SmoothingMode = SmoothingMode.HighQuality;

            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;//如果不填加反锯齿代码效果如图1

            int interval = 15;
            int pointX = 5;
            Rectangle destRect = new Rectangle(190, 10, image.Width, image.Height);
            g.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
            height += 8;
            RectangleF layoutRectangle = new RectangleF(pointX, height, 260f, 85f);
            g.DrawString("资产编号:" + asset[0], font, brush, layoutRectangle);

            height += interval;
            layoutRectangle = new RectangleF(pointX, height, 230f, 85f);
            g.DrawString("资产名称:" + asset[1], font, brush, layoutRectangle);

            //height += interval;
            //layoutRectangle = new RectangleF(pointX, height, 230f, 85f);
            //g.DrawString("类    别:" + asset.Category, font, brush, layoutRectangle);

            //height += interval;
            //layoutRectangle = new RectangleF(pointX, height, 230f, 85f);
            //g.DrawString("规格型号:" + asset.Model, font, brush, layoutRectangle);

            //height += interval;
            //layoutRectangle = new RectangleF(pointX, height, 230f, 85f);
            //g.DrawString("生产厂家:" + asset.Manufacturer, font, brush, layoutRectangle);


            //height += interval;
            //layoutRectangle = new RectangleF(pointX, height, 230f, 85f);
            //g.DrawString("启用时间:" + asset.StartUseTime, font, brush, layoutRectangle);

            //height += interval;
            //layoutRectangle = new RectangleF(pointX, height, 230f, 85f);
            //g.DrawString("资产价格:" + asset.Price, font, brush, layoutRectangle);

            //height += interval;
            //layoutRectangle = new RectangleF(pointX, height, 230f, 85f);
            //g.DrawString("保管单位:" + asset.Department, font, brush, layoutRectangle);

            ////height += interval;
            //layoutRectangle = new RectangleF(pointX + 150, height, 230f, 85f);
            //g.DrawString("保管人:" + asset.Manager, font, brush, layoutRectangle);

            //height += interval;
            //layoutRectangle = new RectangleF(pointX, height, 230f, 85f);
            //g.DrawString("存放地点:" + asset.StoragePlace, font, brush, layoutRectangle);

            //height += interval;
            //layoutRectangle = new RectangleF(pointX, height, 240f, 85f);
            //g.DrawString("备    注:" + asset.Remark, font, brush, layoutRectangle);

            return printPicture;
        }
    }
}



//涉及知识点：

//BarcodeWriter 用于生成图片格式的条码类，通过Write函数进行输出。继承关系如上图所示。

//BarcodeFormat 枚举类型，条码格式

//QrCodeEncodingOptions 二维码设置选项，继承于EncodingOptions，主要设置宽，高，编码方式等信息。

//MultiFormatWriter 复合格式条码写码器，通过encode方法得到BitMatrix。

//BitMatrix 表示按位表示的二维矩阵数组，元素的值用true和false表示二进制中的1和0。
